package com.cat.model.biz.service.api.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alonew.core.commons.util.TimeUtil;
import com.alonew.db.dao.TxCommonDAO;
import com.alonew.json.JSONArray;
import com.alonew.json.JSONException;
import com.alonew.json.JSONObject;
import com.cat.model.biz.logic.BasLogic;
import com.cat.model.biz.logic.OrderLogic;
import com.cat.model.biz.service.admin.SolutionService;
import com.cat.model.biz.service.api.BasOrderService;
import com.cat.model.biz.service.api.ReservationService;
import com.cat.model.biz.service.bs.SmsBS;
import com.cat.model.biz.service.bs.UserBS;
import com.cat.model.common.enumerator.OrderStatus;
import com.cat.model.common.enumerator.SubjectType;
import com.cat.model.common.model.common.BasConfigVO;
import com.cat.model.common.model.common.BasOrderVO;
import com.cat.model.common.model.common.ModelInfoVO;
import com.cat.model.common.model.common.ReservationShortlistVO;
import com.cat.model.common.model.common.ReservationVO;
import com.cat.model.common.model.common.SolutionModelVO;
import com.cat.model.common.model.common.SolutionVO;
import com.cat.model.common.util.Constant;
import com.cat.model.common.util.ErrorCode;
import com.cat.model.common.util.ImageUtil;
import com.cat.model.common.util.PageUtil;
import com.cat.model.dao.mapper.ModelMapper;
import com.cat.model.dao.mapper.UserInfoMapper;
import com.cat.model.web.bean.ReservationBean;
import com.cat.model.web.bean.ReservationShortlistBean;

@Service("reservationService")
public class ReservationServiceImpl implements ReservationService{
	
	@Autowired
	UserBS userBS;
	@Autowired
	SmsBS smsBS;
	@Autowired
	private SolutionService solutionService; 
	@Autowired
	private BasLogic basLogic; 
	@Autowired
	OrderLogic orderLogic;
	@Autowired
	BasOrderService basOrderService;
	@Autowired
	UserInfoMapper userMapper;
	
	@Autowired
	ModelMapper modelMapper;
	
	@Autowired
	private TxCommonDAO txCommonDAO;

	@Override
	public String reservationList(Long userId, int page, int size) {
		List<ReservationVO> reserList = modelMapper.getReservationList(userId);
		
		JSONObject json = ErrorCode.OK.responseJSON();
		List<ReservationBean> beanList = new ArrayList<ReservationBean>();
		if(reserList == null || reserList.size() <= 0){
			try {
				json.put("data", new JSONArray(beanList));
			} catch (JSONException e) {
				return ErrorCode.SERVER_ERROR.response();
			}
			return json.toString();
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		for(ReservationVO vo : reserList){
			ReservationBean bean = new ReservationBean();
			
			bean.setId(vo.getId());
			bean.setModelRequirement(vo.getModelRequirement());
			if(vo.getWorkStartTime()!=null){
				bean.setWorkStartTimeStr(sdf.format(vo.getWorkStartTime()));
			} else {
				bean.setWorkStartTimeStr("");
			}
			if(vo.getWorkEndTime()!=null){
				bean.setWorkEndTimeStr(sdf.format(vo.getWorkEndTime()));
			} else {
				bean.setWorkEndTimeStr("");
			}
			
			bean.setWorkCityCode(vo.getWorkCityCode());
			bean.setWorkAddress(vo.getWorkAddress());
			bean.setWorkType(vo.getWorkType());
			bean.setWorkHours(vo.getWorkHours());
			bean.setServiceBrand(vo.getServiceBrand());
			bean.setPhoneNo(vo.getPhoneNo());
			bean.setName(vo.getName());
			bean.setTotalAmount(vo.getTotalAmount());
			bean.setStatus(vo.getStatus());
			bean.setRemark(vo.getRemark());
			bean.setSubjectType(vo.getSubjectType());
			
			List<ReservationShortlistVO> shortlists = modelMapper.getReservationShortlist(vo.getId());
			ArrayList<ReservationShortlistBean> shortlist = new ArrayList<>();
			if(shortlists!=null&&shortlists.size()>0){
				for(ReservationShortlistVO shortvo : shortlists){	
					ReservationShortlistBean listbean = new ReservationShortlistBean();
					listbean.setId(shortvo.getId());
					listbean.setModelId(shortvo.getModelId());
					listbean.setReservationId(shortvo.getReservationId());
					listbean.setUnitAmount(shortvo.getUnitAmount());
					listbean.setWorkHours(shortvo.getWorkHours());
					if(shortvo.getWorkStartTime()!=null){
						listbean.setWorkStartTimeStr(sdf.format(shortvo.getWorkStartTime()));
					} else {
						listbean.setWorkStartTimeStr("");
					}
					if(shortvo.getWorkEndTime()!=null){
						listbean.setWorkEndTimeStr(sdf.format(shortvo.getWorkEndTime()));
					} else {
						listbean.setWorkEndTimeStr("");
					}
					ModelInfoVO modelInfo = modelMapper.getModelInfo(shortvo.getModelId());
	                if(modelInfo!=null){
	                	listbean.setCoverImage(ImageUtil.wrapImageUrl(modelInfo.getCoverImage()));
	                }
					shortlist.add(listbean);
				}
			}
			bean.setShortlist(shortlist);
			
			beanList.add(bean);
		}
		
		 int[] indexs = PageUtil.getStartAndEnd(page, size, beanList.size());
		 List<ReservationBean> resultList = beanList.subList(indexs[0], indexs[1]);
		
		try {
			json.put("data", new JSONArray(resultList));
		} catch (JSONException e) {
			return ErrorCode.SERVER_ERROR.response();
		}
		
		return json.toString();
	}

	@SuppressWarnings({ "rawtypes", "unused" })
	@Override
	public String createModelReservation(Long userId, ReservationVO reservation,String modelData) {
		reservation.setUserId(userId);
		reservation.setCreateTime(new Date());
		reservation.setStatus("01");//01-未受理
		reservation.setSubjectType(SubjectType.Model.getValue());
		
		txCommonDAO.insert(reservation);
		
		Date minWorkDateTime = null; 
		Date maxWorkDateTime = null;
		int totalWorkHours = 0;
		
		if(StringUtils.isNotEmpty(modelData)){
			try {
				JSONObject jsonObj = new JSONObject(modelData);
				Iterator it = jsonObj.keys();  
		        for (int j = 0; it.hasNext(); j++) {  
		            String str = it.next().toString();  

		            JSONArray array = new JSONArray(jsonObj.get(str).toString());  
//		            System.out.println(array);  
		            for (int i = 0; i < array.length(); i++) {  
		                JSONObject jons = array.getJSONObject(i);  
		                ReservationShortlistVO shortlist = new ReservationShortlistVO();
		                shortlist.setReservationId(reservation.getId());
		                ModelInfoVO modelInfo = modelMapper.getModelInfoByCode(jons.get("modelCode").toString());
		                if(modelInfo!=null){
		                	shortlist.setModelId(modelInfo.getId());
		                }
		                Date workStartDateTime = TimeUtil.parse("yyyy-MM-dd hh:mm:ss", jons.get("timeStart").toString());
		                shortlist.setWorkStartTime(workStartDateTime);
		                Date workEndDateTime = TimeUtil.parse("yyyy-MM-dd hh:mm:ss", jons.get("timeEnd").toString());
		                shortlist.setWorkEndTime(workEndDateTime);
		                shortlist.setWorkHours(new Integer(jons.get("timeLong").toString()));
		                shortlist.setUnitAmount(new BigDecimal(jons.get("price").toString()));
		                if(minWorkDateTime==null){
		                	minWorkDateTime = workStartDateTime;
		                } else {
		                	if(workStartDateTime.before(minWorkDateTime)){
		                		minWorkDateTime = workStartDateTime;
		                	}
		                }
		                if(maxWorkDateTime==null){
		                	maxWorkDateTime = workEndDateTime;
		                } else {
		                	if(workEndDateTime.after(maxWorkDateTime)){
		                		maxWorkDateTime = workEndDateTime;
		                	}
		                }
		                totalWorkHours = totalWorkHours + shortlist.getWorkHours();
		                txCommonDAO.insert(shortlist);
		            }  
		        } 
			} catch (JSONException e) {
				e.printStackTrace();
			}  
		}
		
		reservation.setWorkStartTime(minWorkDateTime);
		reservation.setWorkEndTime(maxWorkDateTime);
		reservation.setWorkHours(totalWorkHours);
		txCommonDAO.updateById(reservation,"workStartTime","workEndTime","workHours");
		
		return ErrorCode.OK.response();
	}

	@Override
	public String confirmModelReservation(Long userId, Long reservationId) {
		ReservationVO reservation = modelMapper.getReservation(reservationId);
		if(null==reservation){
			return ErrorCode.OK.response();
		}
		
		if("01".equals(reservation.getStatus())){
			return ErrorCode.RESERVATION_STATUS_ERROR.response();
		}
		if("03".equals(reservation.getStatus())){
			return ErrorCode.RESERVATION_STATUS_SURE_ERROR.response();
		}
		if("04".equals(reservation.getStatus())){
			return ErrorCode.RESERVATION_STATUS_PAY_ERROR.response();
		}
		reservation.setStatus("03");//已确认
		txCommonDAO.updateById(reservation,"status");
		
		SolutionVO solution = modelMapper.getSolution(new Long(reservationId));
		if(null==solution){
			return ErrorCode.RESERVATION_STATUS_ERROR.response();
		}
		solution.setStatus("02");//02-未支付
		txCommonDAO.updateById(solution,"status");
		
		List<SolutionModelVO> modelList = modelMapper.getSolutionModel(solution.getId());
		Long subjectId = null;
		String subjectName = null;
		String  modelCode=null;
		if(modelList!=null){
			ModelInfoVO modelInfo = modelMapper.getModelInfo(modelList.get(0).getModelId());
            if(modelInfo!=null){
            	subjectName =modelInfo.getName();
            	modelCode = modelInfo.getModelCode();
            }
			if(modelList.size()==1){
				subjectId = modelList.get(0).getModelId();
			} else if(modelList.size()>1){
				subjectName = subjectName+"等"+modelList.size()+"人";
            	modelCode = modelInfo.getModelCode()+"等"+modelList.size()+"人";

			}
		}

		BasOrderVO basOrder = new BasOrderVO();
		basOrder.setSubjectType(SubjectType.Model.getValue());
		basOrder.setSubjectId(subjectId);
		basOrder.setSubjectName(subjectName);
		basOrder.setUserId(userId);
		basOrder.setCreateTime(new Date());
		basOrder.setStatus(OrderStatus.UNPAY.getValue());//01-未付
		basOrder.setTotalAmount(reservation.getTotalAmount());
		basOrder.setName(reservation.getName());
		basOrder.setPhoneNo(reservation.getPhoneNo());
		basOrder.setRefBizCode("01");
		basOrder.setRefBizId(solution.getId());//方案id
		basOrder.setRefBizName("模特预约");
		
		String orderNumber = orderLogic.insertOrderNumber();
		basOrder.setOrderNumber(orderNumber);
		
		txCommonDAO.insert(basOrder);
		SimpleDateFormat time_sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		//短信通知客服
		List<BasConfigVO> contactList =   basLogic.getBasConfigByName(Constant.CUSTOMER_SERVICE_PHONE);
		if(contactList.size()>0){
			BasConfigVO basVO = contactList.get(0);
			String time=time_sdf.format(reservation.getWorkStartTime())+"到"+time_sdf.format(reservation.getWorkEndTime());
			smsBS.sendSMSReservation(basVO.getConfigValue(), reservation.getPhoneNo(), time, modelCode);
		}
		
		JSONObject json = ErrorCode.OK.responseJSON();
		try {
			JSONObject infoJson = new JSONObject();
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			infoJson.put("id", basOrder.getId());
			infoJson.put("orderNumber", basOrder.getOrderNumber());
			infoJson.put("userId", basOrder.getUserId());
			if(basOrder.getCreateTime()!=null){
				infoJson.put("createTime", sdf.format(basOrder.getCreateTime()));
			}else {
				infoJson.put("createTime", "");
			}
			infoJson.put("totalAmount", basOrder.getTotalAmount());
			infoJson.put("phoneNo", basOrder.getPhoneNo());
			infoJson.put("name", basOrder.getName());
			infoJson.put("subjectId", basOrder.getSubjectId());
			infoJson.put("subjectType", basOrder.getSubjectType());
			infoJson.put("subjectName", basOrder.getSubjectName());
			infoJson.put("refBizCode", basOrder.getRefBizCode());
			infoJson.put("refBizId", basOrder.getRefBizId());
			infoJson.put("refBizName", basOrder.getRefBizName());
			
			json.put("data", infoJson);
		} catch (JSONException e) {
			return ErrorCode.SERVER_ERROR.response();
		}
		
		return json.toString();
	}

	/**
	 * 取消模特预约单
	 * */
	public String cancelModelReservation(Long userId, Long reservationId){
		ReservationVO reservation = modelMapper.getReservation(reservationId);
		if(null==reservation){
			return ErrorCode.OK.response();
		}
		if("00".equals(reservation.getStatus())){
			return ErrorCode.RESERVATION_STATUS_CANCEL_ERROR.response();
		}
		if("04".equals(reservation.getStatus())){
			return ErrorCode.RESERVATION_STATUS_PAY_ERROR.response();
		}
		reservation.setStatus("00");//已取消
		txCommonDAO.updateById(reservation,"status");

		JSONObject json = ErrorCode.OK.responseJSON();
		
		return json.toString();
	}
	
	
	@Override
	public String reservationInfo(long reservationId) {
		ReservationVO reservation = modelMapper.getReservation(reservationId);
		if(null==reservation){
			return ErrorCode.OK.response();
		}
		
		
		JSONObject json = ErrorCode.OK.responseJSON();
		try {
			JSONObject infoJson = new JSONObject();
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			infoJson.put("id", reservation.getId());
			infoJson.put("userId", reservation.getUserId());
			if(reservation.getCreateTime()!=null){
				infoJson.put("createTime", sdf.format(reservation.getCreateTime()));
			}else {
				infoJson.put("createTime", "");
			}
			infoJson.put("modelRequirement", reservation.getModelRequirement());
			if(reservation.getWorkStartTime()!=null){
				infoJson.put("workStartTime", sdf.format(reservation.getWorkStartTime()));
			}else {
				infoJson.put("workStartTime", "");
			}
			if(reservation.getWorkEndTime()!=null){
				infoJson.put("workEndTime", sdf.format(reservation.getWorkEndTime()));
			}else {
				infoJson.put("workEndTime", "");
			}
			infoJson.put("workCityCode", reservation.getWorkCityCode());
			infoJson.put("workAddress", reservation.getWorkAddress());
			infoJson.put("workType", reservation.getWorkType());
			infoJson.put("workHours", reservation.getWorkHours());
			infoJson.put("serviceBrand", reservation.getServiceBrand());
			infoJson.put("remark", reservation.getRemark());
			infoJson.put("phoneNo", reservation.getPhoneNo());
			infoJson.put("name", reservation.getName());
			
			String statusDesc = reservation.getStatus();
			if("01".equals(reservation.getStatus())){
				statusDesc = "未受理";
			} else if("02".equals(reservation.getStatus())){
				statusDesc = "已受理";
			}else if("03".equals(reservation.getStatus())){
				statusDesc = "已确认";
			}else if("04".equals(reservation.getStatus())){
				statusDesc = "已支付";
			}
			infoJson.put("status", statusDesc);
			infoJson.put("totalAmount", reservation.getTotalAmount());
			
			List<ReservationShortlistVO> shortlists = modelMapper.getReservationShortlist(reservationId);
			JSONArray styleArray = new JSONArray();
			if(shortlists!=null&&shortlists.size()>0){
				for(ReservationShortlistVO shortlist : shortlists){				
					JSONObject detailJson = new JSONObject();
					detailJson.put("modelId", shortlist.getModelId());
					if(shortlist.getWorkStartTime()!=null){
						detailJson.put("workStartTime", sdf.format(shortlist.getWorkStartTime()));
					} else {
						detailJson.put("workStartTime", "");
					}
					if(shortlist.getWorkEndTime()!=null){
						detailJson.put("workEndTime", sdf.format(shortlist.getWorkEndTime()));
					}else {
						detailJson.put("workEndTime", "");
					}
					detailJson.put("workHours", shortlist.getWorkHours());
					detailJson.put("unitAmount", shortlist.getUnitAmount());
					ModelInfoVO modelInfo = modelMapper.getModelInfo(shortlist.getModelId());
					if(modelInfo!=null){
						detailJson.put("coverImage", ImageUtil.wrapImageUrl(modelInfo.getCoverImage()));
					}
					
					styleArray.put(detailJson);
				}
			}
			infoJson.put("shortlist", styleArray);
			//获取订单信息
			SolutionVO solution = modelMapper.getSolution(new Long(reservationId));
			if(solution!=null){
				BasOrderVO basOrderVO=modelMapper.getBasOrderBySolutionId(solution.getId(),"模特预约");
				if(basOrderVO!=null){
					infoJson.put("orderNumber", basOrderVO.getOrderNumber());
				}
				
			}
			json.put("data", infoJson);
		} catch (JSONException e) {
			return ErrorCode.SERVER_ERROR.response();
		}
		
		return json.toString();
	}

}
